import bluebird from 'bluebird';
import lodash from 'lodash';
import db from '../db';

function add(question, options) {
    return db.exec(trx => {
        const saveQ = trx('xp_questions').forge().save(question, {method: 'insert'});

        return saveQ.then(() => { // eslint-disable-line
            if (options !== null) {
                const optModel = trx('xp_questionoptions');
                const optToSave = options.map(o => optModel.forge().save(o, {method: 'insert'}));
                return bluebird.all(optToSave);
            }
        });
    });
}
function edit(id, question, options) {
    return db.exec(trx => {
        const Question = trx('xp_questions');
        const Option = trx('xp_questionoptions');
        const delOption = Option.where('questionId', id).destroy();
        const updateQ = new Question({id}).save(question);
        let optToSave = [];
        if (options !== null) {
            optToSave = options.map(o => new Option().save(o, {method: 'insert'}));
        }
        const saveOption = bluebird.all(optToSave);

        return delOption.then(() => updateQ).then(() => saveOption);
    });
}

function del(id) {
    return db.exec(trx => {
        const Question = trx('xp_questions');
        const Option = trx('xp_questionoptions');
        const delOption = Option.where('questionId', id).destroy();
        const delQuestion = new Question({id}).destroy();

        return delOption.then(() => delQuestion);
    });
}

function get(id) {
    return db.get('xp_questions').query('where', 'id', id).fetch().then(q => q.serialize());
}
// 改用bookshelf后，获取到的数据格式需要调整一下，以保证与原来使用knex时格式一致
function modifyDetail(queTempData, questions) {
    // 问题以displayOrder的升序排列
    questions = lodash.sortBy(questions.toJSON(), ['displayOrder']);
    questions.forEach(q => {
        // 属性重命名，问题的选项存储在options里面
        q.options = lodash.sortBy(q.questionOptions, ['displayOrder']);
        delete q.questionOptions;

        q.options.forEach(o => { // 删除option中前端不需要的属性
            delete o.questionId;
            delete o.remark;
        });
    });
    return {queTempData, questions};
}
function getQueTempQuestions(queTempId) {
    const questionsQuery = db.get('xp_questions').where('queTempId', queTempId);
    const cols = ['id', 'displayOrder', 'type', 'title', 'remark', 'isRequired'];

    let questions;
    return questionsQuery.fetchAll({
        columns: cols,
        withRelated: ['questionOptions']
    })
        .then(results => { questions = results; })
        .then(() => db.get('xp_questionnaires').forge({id: queTempId}).fetch())
        .then(queTempData => modifyDetail(queTempData, questions));
}
export {add, edit, del, get, getQueTempQuestions};
